﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Taxonomy;

namespace SPRepository
{
    public class SingleTaxonomyFieldType : SimpleFieldType<TaxonomyFieldDto>
    {
        public SingleTaxonomyFieldType(Guid fieldId) : base(fieldId)
        {
        }

        public override TaxonomyFieldDto GetValue(SPListItem item)
        {
            var field = GetField<TaxonomyField>(item);
            var taxonomyFieldValue = TaxonomyFieldUtilities.GetValue(item, field);
            if (taxonomyFieldValue == null)
            {
                return null;
            }
            else
            {
                return new TaxonomyFieldDto(taxonomyFieldValue.Label, new Guid(taxonomyFieldValue.TermGuid));
            }
        }

        public override void SetValue(SPListItem item, TaxonomyFieldDto value)
        {
            var field = GetField<TaxonomyField>(item);
            if (value != null)
            {
                TaxonomyFieldUtilities.SetValue(item, field, value.TermGuid);
            }
            else
            {
                TaxonomyFieldUtilities.SetValue(item, field, null);
            }
        }
    }
}